<!DOCTYPE html>
<html>
  <head>
    <style>
      .waterfall {
        display: grid;
        grid-template-columns: repeat(3, 1fr); /* 增加到5列，进一步减少间隙 */
        grid-auto-rows: 5px; /* 减小基础行高 */
        grid-auto-flow: dense; /* 密集填充模式 */
        gap: 5px; /* 减小间隙 */
        padding: 10px;
        width: 100%;
        box-sizing: border-box;
      }
      .item {
        background: #f0f0f0;
        border-radius: 4px;
        grid-column: span 1; /* 每项占1列 */
        display: flex;
        align-items: center;
        justify-content: center;
        color: #333;
        font-family: Arial, sans-serif;
      }
    </style>
  </head>
  <body>
    <div class="waterfall" id="waterfall"></div>

    <script>
      // 生成25个随机高度的item
      const waterfall = document.getElementById('waterfall');
      const baseRowHeight = 10; // 基础行高

      // 清空现有内容
      waterfall.innerHTML = '';

      for (let i = 0; i < 25; i++) {
        const item = document.createElement('div');
        item.className = 'item';

        // 生成随机高度（150px到350px之间），减少高度差异避免过大间隙
        const randomHeight = Math.floor(Math.random() * 201) + 150;

        // 计算需要跨越的行数
        const rowSpan = Math.ceil(randomHeight / baseRowHeight);

        // 设置样式
        item.style.height = randomHeight + 'px';
        item.style.gridRowEnd = 'span ' + rowSpan;
        item.textContent = 'Item ' + (i + 1) + ' (' + randomHeight + 'px)';

        // 添加随机背景色以增强视觉效果
        const hue = Math.floor(Math.random() * 360);
        item.style.background = `hsl(${hue}, 70%, 80%)`;

        waterfall.appendChild(item);
      }
    </script>
  </body>
</html>
